const errorType = require('../constants/error-type');
const userService = require('../service/user.service');
const md5password = require('../utils/password-handle');

const verifyUser = async (ctx, next) => {
  const {name, password} = ctx.request.body;
  // console.log(name, password);

  // 判断用户名和密码是否为空
  if (!name || !password || name === '' || password === '') {
    const error = new Error(errorType.NAME_OR_PASSWORD_NOT_EMPTY);
    return ctx.app.emit('error', error, ctx);
  }

  const result = await userService.getUserByName(name);
  
  // 判断数据库是否含有当前注册用户名
  if (result.length) {
    const error = new Error(errorType.USER_IS_EXISTENCE);
    return ctx.app.emit('error', error, ctx);
  }

  await next();
}

// 密码加密
const handlePassworld = async (ctx, next) => {
  const {password} = ctx.request.body;
  ctx.request.body.password = md5password(password);

  await next();
}

module.exports = {
  verifyUser,
  handlePassworld
}